﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
using System.Collections.ObjectModel;
using cecbData;
using System.Data;
using cecbClasses.Data_Adapters;
using cecbClasses.Data_Adapters.Project;

namespace CECB.Activity
{
    /// <summary>
    /// Interaction logic for Project_Activity_Insert_Window.xaml
    /// </summary>
    public partial class Project_Activity_Insert_Window : Window
    {
        public ObservableCollection<Activities> ModelListe { get; set; }
        Activities model;

        private DSSEntities dataContext;
        private bool isprojectSelected = false;
        public Project_Activity_Insert_Window()
        {
            InitializeComponent();
            isprojectSelected = false;
            ModelListe = new ObservableCollection<Activities>();
            DataContext = this;
            dataContext = new DSSEntities();
            cecbClasses.Data_Adapters.Slider slid = new cecbClasses.Data_Adapters.Slider();

            ProjectAutocompleteTextBox.ItemsSource = slid.getProjectDetails();
            if (listBoxActivities.Items.Count > 0)
            {
                groupBox.Visibility = System.Windows.Visibility.Visible;
            }
            else groupBox.Visibility = System.Windows.Visibility.Hidden;
        }
        private void textBoxAddActivity_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (textBoxAddActivity.Text.Length > 0)
            {

                (FindResource("drop") as Storyboard).Begin(this);
                listBoxActivities.ItemsSource = new cecbClasses.Data_Adapters.ImpactAndActivity.Func_Activities().getActivityDetailsByName(textBoxAddActivity.Text.Trim());

            }
        }
        private void listBoxActivities_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            List<Activities> list = new List<Activities>();

            if (listBoxActivities.SelectedIndex != -1)
            {

                Activities name = (Activities)listBoxActivities.SelectedItem;

                String x = name.actv_name;
                String y = name.actv_phase;
                String acref = name.actv_reference;
                //   DssEntities cecbContext = new DssEntities();
                //     String y = cecbContext.Components.First(i => i.cmpt_reference == x).cmpt_name.ToString();
                //  MessageBox.Show(name.impt_name + "==="+ y);


                model = new Activities();

                //  model.impt_name= comboBoxComponents.Text;
                try
                {
                    model.actv_name = name.actv_name;
                    model.actv_phase = y;
                    model.actv_reference = acref;
                    ModelListe.Add(model);
                }
                catch (Exception)
                {

                }
            }
        }
        private void textBoxActivitySearch_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (textBoxActivitySearch.Text.Length > 0)
            {

                (FindResource("drop") as Storyboard).Begin(this);
                listBoxActivities.ItemsSource = new cecbClasses.Data_Adapters.ImpactAndActivity.Func_Activities().getActivityDetailsByName(textBoxActivitySearch.Text.Trim());
                if (listBoxActivities.Items.Count > 0)
                {
                    groupBox.Visibility = System.Windows.Visibility.Visible;
                }
                else groupBox.Visibility = System.Windows.Visibility.Hidden;
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (isprojectSelected)
            {

                if (comboBoxComponents.SelectedIndex != -1)
                {
                    if (textBoxAddActivity.Text.Length != 0)
                    {
                        
                         
                      String proRef = ((Projects)ProjectAutocompleteTextBox.SelectedItem).proj_reference.ToString();
                      String refere = new cecbClasses.Data_Adapters.ImpactAndActivity.Func_Activities().InsertNewActivity(textBoxAddActivity.Text, comboBoxComponents.Text, proRef);

                      model = new Activities();
                      model.actv_phase = comboBoxComponents.Text;
                      model.actv_name = textBoxAddActivity.Text;
                      model.actv_reference = refere;
                      ModelListe.Add(model);
                      MessageBox.Show(" New activity saved Successfully", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
                        //if (new cecbClasses.Data_Adapters.ImpactAndActivity.Func_Activities().InsertNewActivity(textBoxAddActivity.Text, comboBoxComponents.Text,  proRef ))
                        //{
                        //    MessageBox.Show("Impact Added Successfully", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
                        //    textBoxAddActivity.Clear();
                        //} 
                        textBoxAddActivity.Clear();
                   }
                    else MessageBox.Show("Please Enter a activity", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else MessageBox.Show("Please Select a phase", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else MessageBox.Show("Please Select a project", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        private void ProjectAutocompleteTextBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            if (((AutoCompleteBox)sender).SelectedItem == null)
            {
                isprojectSelected = false;
                treeViewActivities.Items.Clear();
                textBoxActivitySearch.Clear();
                textBoxAddActivity.Clear();
                return;
                
            }
            else
            {
                isprojectSelected = true;
                try
                {
                    treeViewActivities.Items.Clear();
                    textBoxActivitySearch.Clear();
                    textBoxAddActivity.Clear();
                    cecbClasses.Data_Adapters.Slider slid = new cecbClasses.Data_Adapters.Slider();
                    isprojectSelected = true;
                    Projects proj = (Projects)ProjectAutocompleteTextBox.SelectedItem;
                    ModelListe.Clear();
                    ProjectDetailsWrapPanel.DataContext = slid.getProjectDetailsByRef(proj.proj_reference);
                    fillActivities(proj.proj_reference);

                }
                catch (Exception)
                {

                }
            }
           
        }



        public void fillActivities(String projRef)
        {

            //-------------------------------------------------------------------------------

            IQueryable<Activities> qActivities = (from c in dataContext.ProjectActivities
                                                  join b in dataContext.Activities on c.actv_reference equals b.actv_reference

                                                  where c.proj_reference == projRef
                                                  orderby b.actv_phase
                                                  select b).GroupBy(b => b.actv_phase).Select(x => x.FirstOrDefault());

            int y = 0;
            foreach (Activities act in qActivities)
            {

                treeViewActivities.Items.Add(new TreeViewItem()
                {
                    Header = act.actv_phase//,
                    // FontStyle = FontStyles.Italic,
                    // FontWeight = FontWeights.Bold
                });

                IQueryable<Activities> qImpacts = from c in dataContext.ProjectActivities
                                                  join b in dataContext.Activities on c.actv_reference equals b.actv_reference

                                                  where c.proj_reference == projRef && b.actv_phase == act.actv_phase
                                                  select b;

                foreach (Activities imp in qImpacts)
                {
                    ((TreeViewItem)treeViewActivities.Items[y]).Items.Add(SetTreeViewActivity(imp.actv_name.ToString(),   imp.actv_reference.ToString(), false));
                    ((TreeViewItem)treeViewActivities.Items[y]).IsExpanded = true;
                }
                y++;
            }

        }

        private TreeViewItem SetTreeViewActivity(string text,  String displyVal, Boolean valueType)
        {

            bool isWithValues = valueType;
            TreeViewItem item = new TreeViewItem();

            item.IsExpanded = true;

            StackPanel stack = new StackPanel();
            stack.Orientation = Orientation.Horizontal;


            Label lbl = new Label();
            lbl.Name = "lblImpText";
            lbl.Content = text;
            stack.Children.Add(lbl);
             
            item.Header = stack;

            item.Foreground = Brushes.Brown;
            item.BorderBrush = Brushes.Black;
            item.FontStyle = FontStyles.Italic;
            item.Cursor = Cursors.Hand;
            item.FontSize = 13;
            item.Height = 22;
            item.DisplayMemberPath = displyVal;


            return item;
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            if (dataGrid1.SelectedIndex > -1)
                ModelListe.RemoveAt(dataGrid1.SelectedIndex);
            else
                MessageBox.Show("Nothing has selected to remove", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        }
        
        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {

            if (isprojectSelected)
            {
                if (dataGrid1.Items.Count != 0)
                {
                    if (comboBoxComponents.SelectedIndex != -1)
                    {

                        List<String> phase = new List<string>();
                        List<String> acti = new List<string>();
                        List<String> acref = new List<string>();

                        int rows = dataGrid1.Items.Count;
                        int rows1 = dataGrid1.Items.Count;
                        foreach (Activities row in dataGrid1.Items)
                        {

                            phase.Add(row.actv_phase);
                            acti.Add(row.actv_name);
                            acref.Add(row.actv_reference);
                            rows--;
                            if (rows == 0)
                                break;
                        }


                        if (new cecbClasses.Data_Adapters.ImpactAndActivity.Func_Activities().InsertActivity(phase, acti, acref, rows1, labelProjectReference.Content.ToString()))
                        {
                            MessageBox.Show(dataGrid1.Items.Count + " Activities inserted", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
                            textBoxAddActivity.Text = "";
                            ModelListe.Clear();

                        }
                    }
                    else
                        MessageBox.Show("select the phace", "Error", MessageBoxButton.OK, MessageBoxImage.Error);

                }
                else MessageBox.Show("Add activities", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else MessageBox.Show("Select a project", "Error", MessageBoxButton.OK, MessageBoxImage.Error);



        }

        private void comboBoxComponents_DropDownOpened(object sender, EventArgs e)
        {
            if (!isprojectSelected) {
                MessageBox.Show("Select a project ", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void textBoxAddActivity_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            
        }

        private void textBoxAddActivity_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (comboBoxComponents.SelectedIndex < 0)
            {
                MessageBox.Show("Select a phase", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                e.Handled = true;
            }
        }

        private void textBoxActivitySearch_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (!isprojectSelected)
            {
                MessageBox.Show("Select a project", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                e.Handled = true;
            }
        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

    }
}
